﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace RPCServer.Tool
{
    class KeyValueFileHelper
    {
        static string _Delimiter = "=";

        Dictionary<string, string> _items;

        string _filePath;

        public static bool TryLoad(string filePath, ref Dictionary<string, string> content)
        {
            if (!File.Exists(filePath))
            {
                return false;
            }

            FileStream stream = File.OpenRead(filePath);
            using StreamReader reader = new(stream, Encoding.UTF8);

            while (!reader.EndOfStream)
            {
                string[] kv = reader.ReadLine().Split(_Delimiter);
                content.Add(kv[0], kv[1]);
            }
            return true;
        }

        public void LoadOrCreate(string filePath)
        {
            _filePath = filePath;

            _items = new Dictionary<string, string>();

            if (!File.Exists(_filePath))
            {
                File.Create(_filePath).Close();
                
                return;
            }

            TryLoad(_filePath, ref _items);
        }

        public void Set(string key, string value)
        {
            if (_items.ContainsKey(key))
                _items[key] = value;
            else
                _items.Add(key, value);
        }

        public void Delete(string key)
        {
            _items.Remove(key);
        }

        public void Save()
        {
            File.WriteAllText(_filePath, ToString());
        }

        public static void Save(string filePath, Dictionary<string, string> content)
        {
            File.WriteAllText(filePath, CovertToString(content));
        }

        static string CovertToString(Dictionary<string, string> content)
        {
            StringBuilder sb = new();

            foreach (var item in content)
            {
                sb.AppendLine($"{item.Key}={item.Value}");
            }
            return sb.ToString();
        }

        public override string ToString()
        {
            return CovertToString(_items);
        }
    }
}
